# Filename: jit-mda-check-drbd.sh 
# Usage: jit-mda-check-drbd.sh <imagename> <backupIp>
# Example: jit-mda-check-drbd.sh vm01 10.0.0.2
#
# Checks the BackUp host for DRBD connection a limited number of times,
# waiting between each one according to hardcoded parameters $maxTries and
# $waitTime below.
# Returns 0 when the resource is available.
# Returns 3 when the resource is not available.

imagename=$1
backupip=$2
verify="1"
i="0"
waitTime="60"
maxTries="15"
backupDrbdState=''
readyDrbdState='cs="Connected"'

echo `date +%H:%M:%S` Starting Script $0 $*
if [ -z "$imagename" -o -z "$backupip" ]; then
	echo Incorrect parameters
	echo "Usage: $0 <image name> <backupIP>"
	exit 1
fi

while [ $verify == 1 ]; do
        if [ $i -lt $maxTries ]; then
                echo At `date +%H:%M:%S` hours, verifying DRBD status
				backupDrbdState=`ssh root@$backupip drbdadm status | grep $imagename`;
				if [[ "$backupDrbdState" == *"$readyDrbdState"* ]]; then
                        echo At `date +%H:%M:%S` hours, DRBD available for resource $imagename on server $backupip
                        verify=0
                else
                        i=$[$i+1]
						echo At `date +%H:%M:%S`, resource $imagename unavailable on DRBD server $backupip. Waiting $waitTime more seconds. "($i of $maxTries tries)"
                        sleep $waitTime
                fi
        fi
        if [[ "$i" == "4" ]]; then
                echo `date +%H:%M:%S` : Time limit reached while waiting for resource $imagename on DRBD server $backupip. Quitting.
                verify=3
        fi
done
echo `date +%H:%M:%S` Finishing Script $0
exit $verify

